package com.thinkTank.oa.perm;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.thinkTank.oa.dao.UserMapper;
import com.thinkTank.oa.entity.Role;
import com.thinkTank.oa.entity.User;

/***
 * 登录认证
 * @ 2018-07-20
 * @author dq
 *
 */
@Component
public class MyCustomUserService implements UserDetailsService{

     @Autowired
    private UserMapper userMapper;

    /**
     * 将用户所有角色存储于用户信息中
     * @param username
     * @return
     * @throws UsernameNotFoundException
     * 重写UserDetailsService,登录认证
		认证是由 AuthenticationManager 来管理的，但是真正进行认证的是 AuthenticationManager 
		中定义的 AuthenticationProvider。Spring Security 默认会使用DaoAuthenticationProvider。
		DaoAuthenticationProvider 在进行认证的时候需要一个 UserDetailsService 
		来获取用户的信息 UserDetails。改变认证的方式，就实现 UserDetailsService，返回我们自己userdetails
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    	 //查找用户名是否存在
    	//System.out.println("录入的username值为："+username);
      User user = userMapper.getUserByUsername(username);
    	//System.out.println("111111111111111111");
        if(user == null)
            throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));

       
        //获取用户所有的角色
        List<Role> roles = userMapper.getRolesByUsername(user.getUserName());
        List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
        for (Role role : roles) {
        	
            //封装用户信息和角色信息 到 SecurityContextHolder全局缓存中
            grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        return new org.springframework.security.core.userdetails.User(user.getUserName(), user.getMd5(), grantedAuthorities);
    }
}
